package org.jeecg.modules.wmhb.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wmhb.vo.WmBomResultVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.constant.UserConstant;
import org.springframework.util.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.wmhb.util.WmhbUtil;

/**
 * @Description: 物料产品表
 * @Author: jeecg-boot
 * @Date: 2024-08-31
 * @Version: V1.0
 */
@Api(tags = "物料产品表")
@RestController
@RequestMapping("/wmhb/wmItem")
@Slf4j
public class WmItemController extends JeecgController<WmItem, IWmItemService> {
    @Autowired
    private IWmItemService wmItemService;
    @Autowired
    private IWmItemTypeService wmItemTypeService;

    /**
     * 分页列表查询
     *
     * @param wmItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "物料产品表-分页列表查询")
    @ApiOperation(value = "物料产品表-分页列表查询", notes = "物料产品表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmItem>> queryPageList(WmItem wmItem,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        //获取分类及其子类的物料产品
        List<String> ids = new ArrayList<>();
        if (!StringUtils.isEmpty(wmItem.getWmItemTypeId())) {
            //获取祖先有某个ID的列表
            ids = wmItemTypeService.findInSet(wmItem.getWmItemTypeId());
            ids.add(wmItem.getWmItemTypeId());
            wmItem.setWmItemTypeId(null);//已有where in，等于sql的删除
        }

        QueryWrapper<WmItem> queryWrapper = QueryGenerator.initQueryWrapper(wmItem, req.getParameterMap());
        if (!CollectionUtils.isEmpty(ids)) {
            queryWrapper.in("wm_item_type_id", ids);
        }
        Page<WmItem> page = new Page<WmItem>(pageNo, pageSize);
        IPage<WmItem> pageList = wmItemService.page(page, queryWrapper);
        List<WmItem> wmItemList = new ArrayList<>();
        for(WmItem wmItemChild: pageList.getRecords()){
            wmItemChild.setQrcode(WmhbUtil.generateQrCode(UserConstant.QR_CODE_URL + wmItemChild.getId()));
            wmItemList.add(wmItemChild);
        }
        pageList.setRecords(wmItemList);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmItem
     * @return
     */
    @AutoLog(value = "物料产品表-添加")
    @ApiOperation(value = "物料产品表-添加", notes = "物料产品表-添加")
    @RequiresPermissions("wmhb:wm_item:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WmItem wmItem) {
        if (UserConstant.NOT_UNIQUE.equals(wmItemService.checkItemCodeUnique(wmItem))) {
            return Result.error("新增物料" + wmItem.getCode() + "失败，物料编码已存在");
        }
        if (UserConstant.NOT_UNIQUE.equals(wmItemService.checkItemNameUnique(wmItem))) {
            //return Result.error("新增物料" + wmItem.getCode() + "失败，物料名称已存在");
        }

        if (StringUtils.isEmpty(wmItem.getCode())) {
            String code = (String) FillRuleUtil.executeRule(FillRuleConstant.ITEM, null);
            wmItem.setCode(code);
        }

        if (!StringUtils.isEmpty(wmItem.getWmItemTypeId())) {
            WmItemType wmItemType = wmItemTypeService.getById(wmItem.getWmItemTypeId());
            wmItem.setItemOrProduct(wmItemType.getItemOrProduct());
        }

        wmItemService.save(wmItem);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmItem
     * @return
     */
    @AutoLog(value = "物料产品表-编辑")
    @ApiOperation(value = "物料产品表-编辑", notes = "物料产品表-编辑")
    @RequiresPermissions("wmhb:wm_item:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WmItem wmItem) {
        if (UserConstant.NOT_UNIQUE.equals(wmItemService.checkItemCodeUnique(wmItem))) {
            return Result.error("编辑物料" + wmItem.getCode() + "失败，物料编码已存在");
        }
        if (UserConstant.NOT_UNIQUE.equals(wmItemService.checkItemNameUnique(wmItem))) {
            //return Result.error("编辑物料" + wmItem.getCode() + "失败，物料名称已存在");
        }

        if (!StringUtils.isEmpty(wmItem.getWmItemTypeId())) {
            WmItemType wmItemType = wmItemTypeService.getById(wmItem.getWmItemTypeId());
            wmItem.setItemOrProduct(wmItemType.getItemOrProduct());
        }

        wmItemService.updateById(wmItem);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "物料产品表-通过id删除")
    @ApiOperation(value = "物料产品表-通过id删除", notes = "物料产品表-通过id删除")
    @RequiresPermissions("wmhb:wm_item:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        wmItemService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "物料产品表-批量删除")
    @ApiOperation(value = "物料产品表-批量删除", notes = "物料产品表-批量删除")
    @RequiresPermissions("wmhb:wm_item:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wmItemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "物料产品表-通过id查询")
    @ApiOperation(value = "物料产品表-通过id查询", notes = "物料产品表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmItem> queryById(@RequestParam(name = "id", required = true) String id) {
        WmItem wmItem = wmItemService.getById(id);
        if (wmItem == null) {
            return Result.error("未找到对应数据");
        }
        wmItem.setQrcode(WmhbUtil.generateQrCode(UserConstant.QR_CODE_URL + wmItem.getId()));
        return Result.OK(wmItem);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param wmItem
     */
    @RequiresPermissions("wmhb:wm_item:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmItem wmItem) {
        return super.exportXls(request, wmItem, WmItem.class, "物料产品表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel/{wmContractId}", method = RequestMethod.POST)
    @RequiresPermissions("wmhb:wm_item:importExcel")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            try {
                Workbook workbook = new XSSFWorkbook(file.getInputStream());
                Sheet sheet = workbook.getSheetAt(0); // 假设 BOM 数据在第一个工作表中
                Iterator<Row> rowIterator = sheet.iterator();
                while (rowIterator.hasNext()) {
                    Row row = rowIterator.next();
                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        String cellValue = "";

                        switch (cell.getCellType()) {
                            case STRING:
                                cellValue = cell.getStringCellValue();
                                break;
                            case NUMERIC:
                                cellValue = String.valueOf(cell.getNumericCellValue());
                                break;
                            case BOOLEAN:
                                cellValue = String.valueOf(cell.getBooleanCellValue());
                                break;
                            default:
                                // 忽略其他类型
                                break;
                        }
                        System.out.print(cellValue + "\t"); // 打印单元格的值
                    }
                    System.out.println(); // 每行结束后换行
                }

                return Result.ok("文件导入成功！");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败：" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 获取项目列表
     *
     * @return
     */
    @ApiOperation(value="物料产品表-获取项目列表", notes="物料产品表-获取项目列表")
    @GetMapping(value = "/projectList")
    public Result<List<WmItem>> projectList() {
        List<WmItem> wmItemList = wmItemService.projectList();

        return Result.OK(wmItemList);
    }


}
